package com.hsjk.szwj.module.pay.controller.app.refund;

import cn.hutool.core.util.ObjectUtil;
import com.hsjk.szwj.framework.common.exception.ServiceException;
import com.hsjk.szwj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hsjk.szwj.module.pay.controller.PayApiController;
import com.hsjk.szwj.module.pay.controller.app.refund.vo.QueryRefundOrderReqVO;
import com.hsjk.szwj.module.pay.controller.app.refund.vo.QueryRefundOrderRespVO;
import com.hsjk.szwj.module.pay.dal.dataobject.CommonPayResult;
import com.hsjk.szwj.module.pay.dal.dataobject.order.RefundOrderDO;
import com.hsjk.szwj.module.pay.dal.dataobject.system.MchInfoDO;
import com.hsjk.szwj.module.pay.service.ConfigContextQueryService;
import com.hsjk.szwj.module.pay.service.IMchInfoService;
import com.hsjk.szwj.module.pay.service.RefundOrderService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/25 01:08
 **/
@Tag(name = "应用端 - 查询退款相关接口")
@RestController
@RequestMapping("/refund")
@Validated
@Slf4j
public class QueryRefundOrderController extends PayApiController {
    @Resource
    private RefundOrderService refundOrderService;
    @Resource
    private ConfigContextQueryService configContextQueryService;
    @Resource
    private IMchInfoService mchInfoService;

    /**
     * 查单接口
     **/
    @RequestMapping("/query")
    public CommonPayResult queryRefundOrder() {

        //获取参数 & 验签
        QueryRefundOrderReqVO rq = getRQByWithMchSign(QueryRefundOrderReqVO.class);


        if (ObjectUtil.isNull(rq.getMchRefundId()) && ObjectUtil.isNull(rq.getRefundOrderId())) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "mchRefundNo 和 refundOrderId不能同时为空");
        }
        MchInfoDO mchInfoDO = mchInfoService.getMchInfoById(rq.getMchId());
        RefundOrderDO refundOrder =
                refundOrderService.queryMchOrder(mchInfoDO.getId(),
                        rq.getMchRefundId(), rq.getRefundOrderId());
        if (refundOrder == null) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "订单不存在");
        }

        QueryRefundOrderRespVO bizRes = QueryRefundOrderRespVO.buildByRefundOrder(refundOrder);
        return CommonPayResult.okWithSign(bizRes,
                configContextQueryService.queryMchApp(rq.getMchId(),
                        rq.getAppId()).getAppSecret());
    }
}
